<script setup lang="ts">

import { ref, onMounted, computed } from "vue";
import { FilterMatchMode } from 'primevue/api';
import Toolbar from 'primevue/toolbar';
import IconField from 'primevue/iconfield';
import InputIcon from 'primevue/inputicon';
import FileUpload from 'primevue/fileupload';
import InputNumber from 'primevue/inputnumber';
import InputGroup from 'primevue/inputgroup';
import InputGroupAddon from 'primevue/inputgroupaddon';
import { UploadsImageApi } from "@/api/upload";
import { addPaperApi ,getPaperListApi} from "@/api/paper/index";
import { getExamInfo } from "@/api/exam/index";
import { useUserStore } from "@/stores/modules/user";

import { useConfirm } from "primevue/useconfirm";
const selectedProducts = ref();
const confirm = useConfirm();
// 添加试卷弹框
const addPaperDialog = ref(false);

// 导出excel
const dt = ref();

// 添加试卷数据
const addPaperInfos = ref({
    examId: null,  // 考试id
    score: null,   // 总分
    subject: "",  // 科目
    name: "",   // 试卷名称
    duration: null,// 考试时长
    imgs: []
});


// 返回试卷数据
const papers = ref({
    // 试卷
    examId: null,  // 考试id
    score: null,   // 总分
    subject: "",  // 科目
    name: "",   // 试卷名称
    duration: null,// 考试时长
    startTime: null,// 开始时间
    imgs: [],

    // 答案
    type: "",  // 题型
    questionNumber: "",  // 题号
    questionContent: "",  // 题目内容
    options: [],  // 选项
    paperId: null,  // 试卷id
    difficulty: null,  // 难度系数
    score: null,  // 分数
    answer: "",  // 答案
    answerImg: "",  // 答案图片



});



const filters = ref({
    'global': { value: null, matchMode: FilterMatchMode.CONTAINS },
});

const selectedExam = ref();
// const examNames = ref([
//     { name: '一模' },
//     { name: '二模' },
//     { name: '三模' },
//     { name: '第四次联考' },
// ]);

const selectedSubject = ref();
const subjects = ref([
    { name: '语文' },
    { name: '数学' },
    { name: '化学' },
    { name: '英语' },
    { name: '物理' },
    { name: '政治' },
    { name: '历史' },
    { name: '地理' },
    { name: '思想' },
    { name: '科学' },
    { name: '音乐' },
    { name: '美术' },
    { name: '其他' },

]);

const submitted = ref(false);

// 考试信息数据
const examInfosData = ref([{
    id: 1,
    info: "2024七校联考模拟",
    status: 1,
    date: "2024-2-3"
}]);

// 待上传文件列表
// const fileArray = ref();
// 返回图片url列表
// const fileUrlArray = ref([]);
const openNew = () => {
    // 打开新建页面
    addPaperDialog.value = true;
    getExamInfo().then((res: any) => {
        examInfosData.value = res.data;
    });

};


onMounted(() => {
    getExamInfo().then((res: any) => {
        examInfosData.value = res.data;
    });
});


/**
 * 新建试卷
 */
const onSave = () => {

    addPaperInfos.value.examId = selectedExam.value.id;
    addPaperInfos.value.name = selectedExam.value.info;
    addPaperInfos.value.subject = selectedSubject.value.name;
    const formData = new FormData();
    for (let i = 0; i < files.value.length; i++) {
        // 将每个文件添加到FormData中
        // 'fileList' 是键名，你可以根据需要修改它
        // files[i] 是文件对象
        formData.append('fileList', files.value[i]);
    }

    // 上传图片
    UploadsImageApi(formData).then(res => {
        if (res.code == 200) {
            addPaperInfos.value.imgs = res.data;
            addPaperApi({...addPaperInfos.value}).then(res => {
                if (res.code == 200) {
                    toast.add({ severity: 'success', summary: '成功', detail: '添加试卷成功', life: 3000 });
                    addPaperDialog.value = false;
                }
            }).catch(err => {
                toast.add({ severity: 'error', summary: '失败', detail: '新建试卷失败', life: 3000 });
            });
        }
    }).catch(err => {
        toast.add({ severity: 'error', summary: '上传失败', detail: '图片上传错误', life: 3000 });
    });
};



const Base64Uploader = (event: any) => {

};

import { usePrimeVue } from 'primevue/config';
import { useToast } from "primevue/usetoast";
import { start } from "repl";

const $primevue = usePrimeVue();
const toast = useToast();

const totalSize = ref(0);
const totalSizePercent = ref(0);
const files = ref([]);



const onRemoveTemplatingFile = (file: any, removeFileCallback: any, index: any) => {
    removeFileCallback(index);
    totalSize.value -= parseInt(formatSize(file.size));
    totalSizePercent.value = totalSize.value / 10;


};

// 清空上传图片列表
const onClearTemplatingUpload = (clear: any) => {
    clear();
    totalSize.value = 0;
    totalSizePercent.value = 0;
};

const onSelectedFiles = (event: any) => {
    // console.log(event);
    files.value = event.files;
    files.value.forEach((file: any) => {
        totalSize.value += parseInt(formatSize(file.size));
    });



};

const onTemplatedUpload = () => {
    toast.add({ severity: "info", summary: "Success", detail: "File Uploaded", life: 3000 });
};

const formatSize = (bytes: number) => {
    const k = 1024;
    const dm = 3;
    const sizes = $primevue.config.locale.fileSizeTypes;
    if (bytes === 0) {
        return `0 ${sizes[0]}`;
    }
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    const formattedSize = parseFloat((bytes / Math.pow(k, i)).toFixed(dm));
    return `${formattedSize} ${sizes[i]}`;
};

const exportCSV = (e: any) => {
    dt.value.exportCSV();
};




const deleteConfirm = () => {
    confirm.require({
        message: '你确定要删除这个记录?',
        header: '删除提醒',
        icon: 'pi pi-info-circle',
        rejectLabel: '取消',
        acceptLabel: '删除',
        rejectClass: 'p-button-secondary p-button-outlined',
        acceptClass: 'p-button-danger',
        accept: () => {
            toast.add({ severity: 'success', summary: '成功', detail: '删除考试成功', life: 3000 })
        },
        // reject: () => {
        //     toast.add({ severity: 'error', summary: '失败', detail: '删除考试失败', life: 3000 });
        // }
    });
};


</script>

<template>
    <Toolbar class="mb-4 p-4">
        <template #start>
            <Button label="新建" icon="pi pi-plus" severity="success" class="mr-2" @click="openNew" />
            <Button label="删除" icon="pi pi-trash" severity="danger" @click="confirmDeleteSelected"
                :disabled="!selectedProducts || !selectedProducts.length" />
        </template>

        <template #end>
            <Button label="Export" icon="pi pi-upload" severity="help" @click="exportCSV($event)" />
        </template>
    </Toolbar>
    <DataTable ref="dt" :value="examInfosData" v-model:selection="selectedProducts" dataKey="id" :paginator="true"
        :rows="10" :filters="filters"
        paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
        :rowsPerPageOptions="[5, 10, 25]" currentPageReportTemplate="显示 {first} to {last} of {totalRecords} 数据">
        <template #header>
            <div class="flex flex-wrap gap-2 items-center justify-between">
                <h4 class="m-0">试卷管理</h4>
                <IconField iconPosition="left">
                    <InputIcon>
                        <i class="pi pi-search" />
                    </InputIcon>
                    <InputText v-model="filters['global'].value" placeholder="Search..." />
                </IconField>
            </div>
        </template>
        <ConfirmDialog class="w-80 h-30"></ConfirmDialog>
        <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
        <Column field="id" header="id" sortable style="max-width:3rem"></Column>
        <Column field="id" header="科目" sortable style="max-width:3rem"></Column>
        <Column field="info" header="试卷名称" sortable style="max-width:10rem"></Column>
        <Column field="info" header="总分" sortable style="max-width:10rem"></Column>
        <Column field="status" header="考试时长" sortable style="max-width:3rem">
            <template #body="slotProps">
                <!-- <Tag :value="slotProps.data.status == 0 ? '公开' : '隐藏'"
                    :severity="getStatusLabel(slotProps.data.status)" /> -->
            </template>
        </Column>
        <Column field="createTime" header="创建时间" sortable style="min-width:16rem">
            <template #body="slotProps">
                <!-- {{ formatDate(slotProps.data.createTime) }} -->
            </template>
        </Column>
        <Column :exportable="false" style="min-width:8rem">
            <template #body="slotProps">
                <Button icon="pi pi-pencil" outlined rounded class="mr-2" @click="addExamInfo(slotProps.data)" />
                <Button icon="pi pi-trash" outlined rounded severity="danger" @click="deleteConfirm" />
            </template>
        </Column>
    </DataTable>

    <!--  添加试卷弹框-->
    <Dialog v-model:visible="addPaperDialog" modal header="添加考试" class="w-[45rem] max-w-screen-md">
        <Divider class="mt-0" />
        <div class="flex items-center gap-3 mb-3">
            <Dropdown v-model="selectedExam" :options="examInfosData" optionLabel="info" placeholder="选择考试名称"
                class="w-full md:w-14rem" />
            <Dropdown v-model="selectedSubject" :options="subjects" optionLabel="name" placeholder="选择科目"
                class="w-full md:w-14rem" />
        </div>
        <div class="flex items-center gap-3 mb-3">
            <label class="font-semibold w-6rem">试卷名称</label>
            <InputText v-model="addPaperInfos.name" class="flex-auto" autocomplete="off" />
        </div>
        <div class="flex items-center gap-3 mb-3">
            <label class="font-semibold w-6rem">分数</label>
            <InputNumber v-model="addPaperInfos.score" placeholder="总分" />
        </div>
        <div class="flex items-center gap-3 mb-3">
            <label class="font-semibold w-6rem">时长</label>
            <InputGroup class="w-60">
                <InputNumber placeholder="时长" v-model="addPaperInfos.duration" />
                <InputGroupAddon>分钟</InputGroupAddon>
            </InputGroup>
        </div>
        <FileUpload name="demo[]" url="/api/upload" @upload="Base64Uploader($event)" :multiple="true" accept="image/*"
            :maxFileSize="1000000" @select="onSelectedFiles">
            <template #header="{ chooseCallback, clearCallback, files }">
                <div class="flex flex-wrap justify-between items-center flex-1 gap-2">
                    <div class="flex gap-2">
                        <Button @click="chooseCallback()" icon="pi pi-images" rounded outlined></Button>
                        <Button @click="onClearTemplatingUpload(clearCallback)" icon="pi pi-times" rounded outlined
                            severity="danger" :disabled="!files || files.length === 0"></Button>
                    </div>
                    <ProgressBar :value="totalSizePercent" :showValue="false"
                        :class="['md:w-20rem h-1rem w-full md:ml-auto', { 'exceeded-progress-bar': totalSizePercent > 100 }]">
                        <span class="white-space-nowrap">{{ totalSize }}B / 1Mb</span>
                    </ProgressBar>
                </div>
            </template>
            <template #content="{ files, uploadedFiles, removeUploadedFileCallback, removeFileCallback }">
                <div class="flex flex-wrap gap-3">
                    <div v-for="(file, index) of files" :key="file.name + file.type + file.size"
                        class="card m-0 p-2 flex flex-col border-1 surface-border items-center gap-2">
                        <div>
                            <img role="presentation" :alt="file.name" :src="file.objectURL" width="100" height="50" />
                        </div>
                        <span class="font-semibold">{{ file.name }}</span>
                        <div>{{ formatSize(file.size) }}</div>
                        <Badge value="Pending" severity="warning" />
                        <Button icon="pi pi-times" @click="onRemoveTemplatingFile(file, removeFileCallback, index)"
                            outlined rounded severity="danger" />
                    </div>
                </div>
            </template>
            <template #empty>
                <div class="flex items-center justify-center flex-col">
                    <i class="pi pi-cloud-upload border-2 border-circle p-5 text-8xl text-400 border-400" />
                    <p class="mt-4 mb-0">上传试卷</p>
                </div>
            </template>
        </FileUpload>
        <div class="flex justify-end gap-2 mt-3">
            <Button type="button" label="取消" severity="secondary" @click="addPaperDialog = false"></Button>
            <Button type="button" label="添加" @click="onSave"></Button>
        </div>
    </Dialog>
</template>
<style scoped></style>